package com.line.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.line.model.pojo.MySqlPojo;
import com.line.tools.util.StringBasicUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(DataSourceConfig.class)
@ConfigurationProperties(prefix = "com.line.datasource")
public class DataSourceConfig {
	private static Logger log = LoggerFactory.getLogger(DataSourceConfig.class);

	private MySqlPojo mysql;

	/**
	 * 加载sswMysql数据源
	 *
	 * @return 数据源
	 */
	@Primary // 优先级
	@Bean(name = "mysqlDs") // 设置数据源名称，通过byName注入
	@Qualifier("mysqlDs")
	public DataSource mysqlDataSource() {
		// 设置链接池配置
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(mysql.getDriver()); // 驱动类
		dataSource.setUrl(mysql.getUrl()); // 链接地址
		dataSource.setUsername(mysql.getUsername()); // 用户名
		dataSource.setPassword(mysql.getPassword()); // 密码
		if (!StringBasicUtils.isBlank(mysql.getInitialSize())) {
			dataSource.setInitialSize(Integer.parseInt(mysql.getInitialSize())); // 设置初始化物理连接池的个数
		}
		if (!StringBasicUtils.isBlank(mysql.getMaxActive())) {
			dataSource.setMaxActive(Integer.parseInt(mysql.getMaxActive())); // 设置最大的连接数
		}
		if (!StringBasicUtils.isBlank(mysql.getMinIdle())) {
			dataSource.setMinIdle(Integer.parseInt(mysql.getMinIdle())); // 设置最小的连接数
		}
		// 设置预知性要启用PSCache，必须配置大于0，当大于0时，poolPreparedStatements自动触发修改为true。
		// 在Druid中，不会存在Oracle下PSCache占用内存过多的问题，
		if (!StringBasicUtils.isBlank(mysql.getMaxOpenPreparedStatements())) {
			dataSource.setMaxOpenPreparedStatements(Integer.parseInt(mysql.getMaxOpenPreparedStatements()));
		}
		dataSource.setValidationQuery("SELECT 1");
		log.info("------Load mysql config-------");
		log.info("sswMysql datasource:" + mysql.toString());
		log.info("-----Load mysql config success!");
		return dataSource;
	}

	/**
	 * 将JDBCTemplate注入容器
	 *
	 * @return
	 */
	@Bean
	@Qualifier("mysqlJdbcTemplate")
	public JdbcTemplate mysqlJdbcTemplate() {
		return new JdbcTemplate(this.mysqlDataSource());
	}

	public MySqlPojo getMysql() {
		return mysql;
	}

	public void setMysql(MySqlPojo mysql) {
		this.mysql = mysql;
	}

}
